

const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

const { isValidPassword, isValidUsername } = require('./verify.js')
const db = require('../db/index.js')
const config = require('../config.js')

// 登录
const login = async (req, res) => {
    const userInfo = req.body
    if (!userInfo) {
        return res.cc('请求体不能为空', 10)
    }
    if (!userInfo.username || !userInfo.password) {
        return res.cc('信息不能为空', 10)
    }
    const { username, password } = userInfo

    try {
        const sqlStr = 'select * from users where username=?'
        const [results] = await db.query(sqlStr, [username])
        if (results.length === 0 || !results[0].status) {
            return res.cc('账号不存在, 请先注册', 1)
        }
        if (!bcrypt.compareSync(password, results[0].password)) {
            return res.cc('密码错误', 2)
        }

        const tokenInfo = {
            uid: results[0].uid,
            username: results[0].username,
            nickname: results[0].nickname,
            status: results[0].status
        }
        const tokenStr = jwt.sign(tokenInfo, config.jwtSecretKey, { expiresIn: config.expiresIn })

        res.send({
            code: 0,
            msg: '登陆成功',
            data: {
                ...tokenInfo,
                avatar: results[0].avatar_path,
                token: 'Bearer ' + tokenStr
            }

        })
    } catch (err) {
        if (db.isDatabaseError(err)) {
            console.log('Error: login-> ', err.message)
            return res.cc(err, 30)
        } else {
            throw err
        }
    }
}


// 注册
const register = async (req, res) => {
    const userInfo = req.body
    if (!userInfo) {
        return res.cc('请求体不能为空', 10)
    }
    if (!userInfo.username || !userInfo.password) {
        return res.cc('信息不能为空', 10)
    }
    let { username, password } = userInfo

    try {
        // 访问数据库
        let sqlStr = 'select * from users where username=?'
        let [results] = await db.query(sqlStr, [username])
        if (results.length > 0) {
            return res.cc('已有账号', 1)
        }
        if (!isValidUsername(username)) {
            return res.cc('用户名不合法', 3)
        }
        if (!isValidPassword(password)) {
            return res.cc('密码不合法', 2)
        }
        // 哈希加密密码
        password = bcrypt.hashSync(password, 10)
        // 写入数据库
        sqlStr = 'insert into users (username,password) values (?,?)'
            ;[results] = await db.query(sqlStr, [username, password])
        if (results.affectedRows !== 1) {
            return res.cc('注册失败, 请稍后再试', 30)
        }
        return res.send({
            code: 0,
            msg: '注册成功',
            data: {
                username
            }

        })


    } catch (err) {
        if (db.isDatabaseError(err)) {
            console.log('Error: register-> ', err.message)
            return res.cc(err, 30)
        } else {
            throw err
        }
    }
}

module.exports = {
    login,
    register
}